//
//  HotCommentViewController.m
//  project
//
//  Created by lanou on 15/10/30.
//  Copyright © 2015年 lanou. All rights reserved.
//

#import "HotCommentViewController.h"
#import "PKRequestManager.h"
#import "StrategyCommentsModel.h"
#import "commentsTableViewCell.h"
#import "LoginViewController.h"
@interface HotCommentViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>

@property (nonatomic, strong)UITableView *mainTableView;
@property (nonatomic, strong)UITextField *sendTF;
@property (nonatomic, strong)UIView *footview;
@property (nonatomic, strong)NSMutableArray *dataArr;
@end

@implementation HotCommentViewController

-(void)requestData
{
    NSString *btnStr = [NSString stringWithFormat:@"http://api.liwushuo.com/v2/items/%@/comments?limit=20&offset=0",_contentId];
    [PKRequestManager requestWithTypeP:GET urlString:btnStr parDic:nil finish:^(NSData *data) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        _dataArr = [NSMutableArray arrayWithCapacity:0];
        for (NSDictionary *dic in dict[@"data"][@"comments"]) {
            StrategyCommentsModel *model = [[StrategyCommentsModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            [_dataArr addObject:model];
        }
        NSLog(@"%ld",_dataArr.count);
        [self.mainTableView reloadData];
    } error:^(NSError *error) {
        
    }];

}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    UILabel *titlelabel = [[UILabel alloc]initWithFrame:CGRectMake((kWidth - 40)/2, 10, 40, 30)];
    titlelabel.text = @"评论";
    titlelabel.textColor = [UIColor whiteColor];
    self.navigationItem.titleView = titlelabel;
    
    self.navigationItem.title = @"评论";
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    [self.navigationItem.leftBarButtonItem setTitle:@"  "];
    
  self.view.backgroundColor = [[UIColor alloc]initWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1];
    _mainTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kWidth, kHeight - 40)];
    _mainTableView.delegate = self;
    _mainTableView.dataSource = self;
    _mainTableView.tableFooterView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, 0)];
    [self.view addSubview:_mainTableView];
    [self.mainTableView registerClass:[commentsTableViewCell class] forCellReuseIdentifier:@"commentsTableViewCell"];
    [self requestData];
    _footview = [[UIView alloc]initWithFrame:CGRectMake(0,kHeight - 40, kWidth, 40)];
    _footview.backgroundColor = [[UIColor alloc]initWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1];;
    
    [self.view addSubview:_footview];
    
    _sendTF = [[UITextField alloc]initWithFrame:CGRectMake(10, 5, kWidth - 100, 30)];
    _sendTF.borderStyle = UITextBorderStyleRoundedRect;
    _sendTF.backgroundColor = [UIColor whiteColor];
    _sendTF.placeholder = @"请输入";
    _sendTF.delegate = self;
    [_footview addSubview:_sendTF];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    UIButton *sendBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    sendBtn.frame = CGRectMake(kWidth - 50 , 10, 40, 20);
    [sendBtn setTitle:@"发送" forState:UIControlStateNormal];
    [sendBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [sendBtn addTarget:self action:@selector(didSend:) forControlEvents:UIControlEventTouchUpInside];
    [_footview addSubview:sendBtn];
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Incomplete implementation, return the number of sections
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    commentsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"commentsTableViewCell" forIndexPath:indexPath];
    
    cell.configuremodel = self.dataArr[indexPath.row];
    return cell;
}

- (void)didSend:(UIButton *)btn
{
    NSUserDefaults *share = [NSUserDefaults standardUserDefaults];
    if (([share valueForKey:@"nickname"] == nil||[[share valueForKey:@"nickname"]isEqualToString:@""])) {
        LoginViewController *loginVC = [[LoginViewController alloc]init];
        UINavigationController *loginNC = [[UINavigationController alloc]initWithRootViewController:loginVC];
        [self presentViewController:loginNC animated:YES completion:nil];
    }
    else
    {
        NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
        parDic[@"_"] = [[NSUserDefaults standardUserDefaults]valueForKey:@"updated_at"];
        parDic[@"content"] = [_sendTF.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSString *str = [NSString stringWithFormat:@"http://api.liwushuo.com/v2/posts/%@/comments",_contentId];
        [PKRequestManager requestWithTypeP:POST urlString:str parDic:parDic finish:^(NSData *data) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            if ([dic[@"code"] integerValue] != 200) {
                UIAlertView *alertVie = [[UIAlertView alloc]initWithTitle:@"评论失败" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alertVie show];
            }
            else{
                
                [_sendTF resignFirstResponder];
                [UIView animateWithDuration:1 animations:^{
                    _footview.frame = CGRectMake(0,kHeight - 40, kWidth, 40);
                }];
                [self requestData];
                
            }
            
        } error:^(NSError *error) {
            
        }];
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [commentsTableViewCell heightforModel:self.dataArr[indexPath.row]];
}


- (void)keyboardWillShow:(NSNotification *)aNotification
{
    //获取键盘的高度
    NSDictionary *userInfo = [aNotification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    int height = keyboardRect.size.height;
    [UIView animateWithDuration:2 animations:^{
        _footview.frame = CGRectMake(0, kHeight - height - 40, kWidth, 40);
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
